package jbase.project.system.net.http;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class HttpHeaders {

	private List<String> headers;

	public HttpHeaders() {
		super();
		this.headers = new ArrayList<>();
	}

	public HttpHeaders(String headers) {
		super();
		this.headers = new ArrayList<>();
		String lines[] = headers.split("\\r\\n");
		for (int i = 0; i < lines.length; i++) {
			String line = lines[i];
			if (line != null && !line.trim().equals("")) {
				this.headers.add(line);
			}
		}
	}

	public boolean lineMatch(int lineNo, String regex) {
		return this.headers.get(lineNo).matches(regex);
	}

	public boolean insertLine(int index, String httpFirstLine) {
		headers.add(index, httpFirstLine);
		return true;
	}

	public boolean insertLine(String httpHeader) {
		headers.add(httpHeader);
		return true;
	}

	public boolean insertOrUpdateLine(String regex, String target) {
		if (!replaceLine(regex, target)) {
			headers.add(target);
		}
		return true;
	}

	public boolean replaceLine(String regex, String target) {
		return replaceLine(Pattern.compile(regex), target);
	}

	public boolean replaceLine(Pattern regex, String target) {
		boolean findit = false;
		int size = this.headers.size();
		for (int i = 0; i < size; i++) {
			String line = this.headers.get(i);
			Matcher m = regex.matcher(line);
			if (m.matches()) {
				findit = true;
				this.headers.set(i, target);
			}
		}
		return findit;
	}

	public boolean setLine(int lineNo, String target) {
		this.headers.set(lineNo, target);
		return true;
	}

	public int lineCount() {
		return this.headers.size();
	}

	public boolean removeLine(String regex) {
		return removeLine(Pattern.compile(regex));
	}

	public boolean removeLine(int lineNo) {
		this.headers.remove(lineNo);
		return true;
	}

	public boolean removeLine(Pattern regex) {
		boolean findit = false;
		int size = this.headers.size();
		for (int i = 0; i < size; i++) {
			String line = this.headers.get(i);
			Matcher m = regex.matcher(line);
			if (m.matches()) {
				findit = true;
				this.headers.remove(i);
				size--;
				i--;
			}
		}
		return findit;
	}

	@Override
	public String toString() {
		StringBuffer headers = new StringBuffer();
		int size = this.headers.size();
		for (int i = 0; i < size; i++) {
			String line = this.headers.get(i);
			headers.append(line + "\r\n");
		}
		headers.append("\r\n");
		return headers.toString();
	}

	public static void main(String[] s) {
		List<String> ss = new ArrayList<>();
		ss.add("a");
		ss.add("b");
		ss.add("c");
		print(ss);
		System.out.println();
		ss.add(0, "-A");
		print(ss);
	}

	private static void print(List<String> list) {
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}
